package com.cxs.controller;

import com.cxs.model.User;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Project: file-upload-demo
 * @Author: cxs2014501@163.com
 * @Create: 2023/3/6 16:51
 * @Description:
 **/
@RestController
public class UserController {

    private static final String PATH = "E:\\ideaProjects\\aaa\\file-upload-demo\\images";

    @PostMapping("/upload")
    public Object saveUser(User user, @RequestParam("file") MultipartFile file){
        try {
            if (!ObjectUtils.isEmpty(file)) {
                // 获取源文件的名字
                String originalFilename = file.getOriginalFilename();
                if (StringUtils.hasLength(originalFilename)) {
                    // 进行文件上传
                    String fullPath = PATH + File.separator + originalFilename;
                    File f = new File(fullPath);
                    if (!f.exists()) {
                        f.createNewFile();
                    }
                    file.transferTo(f);
                    user.setAvatar(fullPath);
                }
            }
            System.out.println(user);
            // 保存user 如 userService.saveUser(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
